package com.qqtop10.manager.controller;

import java.io.File;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.qqtop10.manager.model.Admin;
import com.qqtop10.manager.model.Result;
import com.qqtop10.manager.model.Shop;
import com.qqtop10.manager.model.User;
import com.qqtop10.manager.service.AddressService;
import com.qqtop10.manager.service.AdminService;
import com.qqtop10.manager.service.ShopService;
import com.qqtop10.manager.service.UserService;
import com.qqtop10.manager.utils.FolderPath;
import com.qqtop10.manager.utils.LogHelper;
import com.qqtop10.manager.utils.MD5;
import com.qqtop10.manager.utils.RandomUtils;
import com.qqtop10.manager.utils.oss.OSSFilePath;
import com.qqtop10.manager.utils.oss.OSSUploadUtils;

@Controller
@RequestMapping("/manager/proprietary/")
public class ProprietaryController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(ProprietaryController.class);
	@Autowired
	@Qualifier("shopService")
	private ShopService shopService;

	@Autowired
	@Qualifier("userService")
	private UserService userService;

	@Autowired
	@Qualifier("adminService")
	private AdminService adminService;

	@Autowired
	@Qualifier("addressService")
	private AddressService addressService;

	/**
	 * 编辑商店信息
	 * 
	 * @param request
	 * @return
	 */

	@RequestMapping("shopInfoEdit.do")
	@ResponseBody
	public Result shopInfoEdit(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "sfz", required = false) MultipartFile mfsfz,
			@RequestParam(value = "yyzz", required = false) MultipartFile mfyyzz,
			@RequestParam(value = "logoi", required = false) MultipartFile mflogo, Shop shop) {
		Result result = null;
		String path = FolderPath.getRootPath() + File.separator + "files" + File.separator;
		String dir = "/files/";
		File dirFile = new File(path);
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}
		Admin admin = super.getLogind();
		try {
			result = new Result(1);
			if (admin.getUser_uuid() == null) {
				result.setCode(99);
				result.setMsg("操作失败：未关联用户");
				logger.info("操作失败：未关联用户");
			} else {
				// uuid
				shop.setUuid(RandomUtils.makeUUID());
				// 如果身份证不为空
				if (mflogo != null && !mflogo.isEmpty()) {
					String name = mflogo.getOriginalFilename();
					String suffix = name.substring(name.lastIndexOf(".") + 1, name.length());
					String newName = shop.getUuid() + "logo." + suffix;
					shop.setLogo(OSSFilePath.OSSDOMAIN + "/images" + dir + newName);
					
					// 保存文件至OSS，原有的保存至本地的代码可舍弃
					OSSUploadUtils ossUploadUtils = new OSSUploadUtils();
					// 图片上传OSS
					ossUploadUtils.uploadFile(OSSFilePath.PROPRIETARY + newName, mflogo);
					// 关闭OSS客户端
					ossUploadUtils.closeOssClient();
					
//					mflogo.transferTo(new File(path + newName));
				}
				if (shopService.selectByUserUuid(admin.getUser_uuid()) == null) {
					shop.setName(null);
					// user_uuid
					shop.setUser_uuid(admin.getUser_uuid());
					// 创建时间
					shop.setCreatetime(new Date());
					// 创建者
					shop.setCreator(super.getLogindUuid());
					// 身份证
					shop.setIdcard("");
					// 营业执照
					shop.setBusiness_licence("");
					// 行业类型
					shop.setIndustry_category_uuid("");
					// 状态
					shop.setStatus(1);
					// 类型
					shop.setShop_type(1);
					// 是否删除
					shop.setIsdeleted(false);
					// 省份id
					shop.setProvince_id(addressService.selectByFullName("中国," + shop.getProvince()).getId());
					// 城市id
					shop.setCity_id(
							addressService.selectByFullName("中国," + shop.getProvince() + "," + shop.getCity()).getId());
					// 区域id
					shop.setDistrict_id(addressService
							.selectByFullName(
									"中国," + shop.getProvince() + "," + shop.getCity() + "," + shop.getDistrict())
							.getId());
					int i = shopService.insertSelective(shop);
					if (i > 0) {
						result.setCode(1);
						result.setMsg("操作成功！");
						logger.info("操作成功！");
						Admin Tempadmin = (Admin) getRequest().getSession().getAttribute("Logind");
						LogHelper.Log(Tempadmin.getAccount(),"后台店铺管理模块","编辑店铺成功",LogHelper.getLocalIp(getRequest()),Tempadmin.getAccount(),"",true);

					} else {
						result.setCode(99);
						result.setMsg("操作失败！");
						logger.info("操作失败！");
					}
				} else {
					// // 如果身份证不为空
					// if (mfsfz != null && !mfsfz.isEmpty()) {
					// String name = mfsfz.getOriginalFilename();
					// String suffix = name.substring(name.lastIndexOf(".") + 1,
					// name.length());
					// String newName = shop.getUuid() + "sfz." + suffix;
					// shop.setIdcard(dir + newName);
					// mfsfz.transferTo(new File(path + newName));
					// }
					// // 如果营业执照不为空
					// if (mfyyzz != null && !mfyyzz.isEmpty()) {
					// String name = mfyyzz.getOriginalFilename();
					// String suffix = name.substring(name.lastIndexOf(".") + 1,
					// name.length());
					// String newName = shop.getUuid() + "yyzz." + suffix;
					// shop.setBusiness_licence(dir + newName);
					// mfyyzz.transferTo(new File(path + newName));
					// }
					shop.setUser_uuid(admin.getUser_uuid());
					int i = shopService.updateByUserUuidSelective(shop);
					if (i > 0) {
						result.setCode(1);
						result.setMsg("操作成功！");
						logger.info("操作成功！");
					} else {
						result.setCode(99);
						result.setMsg("操作失败！");
						logger.info("操作失败！");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("操作成功：" + e.getMessage());
		}
		return result;
	}

	@RequestMapping("userUpdate.do")
	@ResponseBody
	public Result userUpdate(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "head", required = false) MultipartFile MFhead, User input) {
		if (input == null) {
			input = new User();
		}
		Result result = new Result(1);
		Admin admin = super.getLogind();
		try {
			if (super.getLogind().getUser_uuid() == null || super.getLogind().getUser_uuid().equals("")) {
				admin.setUser_uuid(RandomUtils.makeUUID());
				input.setUuid(admin.getUser_uuid());
				input.setPassword(new MD5().getMD5("admin123"));
				input.setIsdeleted(false);
				input.setStatus(0);
				input.setType(1);
				input.setCreatetime(new Date());
				input.setCreator(admin.getUuid());
//				File dirFile = new File(FolderPath.getRootPath() + "/userhead/");
//				if (!dirFile.exists()) {
//					dirFile.mkdirs();
//				}
				if (MFhead != null && !MFhead.isEmpty()) {
					String name = MFhead.getOriginalFilename();
					String suffix = name.substring(name.lastIndexOf(".") + 1, name.length());
					String newName = input.getUuid() + "." + suffix;
					// 保存文件至OSS，原有的保存至本地的代码可舍弃
					OSSUploadUtils ossUploadUtils = new OSSUploadUtils();
					// 图片上传OSS
					ossUploadUtils.uploadFile(OSSFilePath.USERHEAD + newName, MFhead);
					// 关闭OSS客户端
					ossUploadUtils.closeOssClient();
//					MFhead.transferTo(new File(dirFile.getPath() + "/" + newName));
					input.setHead_sculpture(OSSFilePath.OSSDOMAIN + "/userhead/" + newName);
				}
				if (userService.insertSelective(input) > 0) {
					adminService.updateUserUuid(admin);
					result.setCode(1);
					result.setMsg("操作成功!");
					Admin Tempadmin = (Admin) getRequest().getSession().getAttribute("Logind");
					LogHelper.Log(Tempadmin.getAccount(),"后台店铺管理模块","更新店铺成功",LogHelper.getLocalIp(getRequest()),Tempadmin.getAccount(),"",true);

				} else {
					result.setCode(99);
					result.setMsg("操作失败：新增失败");
				}
			} else {
				if (input.getUuid() != null && !input.getUuid().equals("")) {
					result.setCode(99);
					result.setMsg("操作失败：关联用户已存在");
				} else {
					input.setAccount(null);
					input.setUuid(admin.getUser_uuid());
//					File dirFile = new File(FolderPath.getRootPath() + "/userhead/");
//					if (!dirFile.exists()) {
//						dirFile.mkdirs();
//					}
					if (MFhead != null && !MFhead.isEmpty()) {
						String name = MFhead.getOriginalFilename();
						String suffix = name.substring(name.lastIndexOf(".") + 1, name.length());
						String newName = input.getUuid() + "." + suffix;
						// 保存文件至OSS，原有的保存至本地的代码可舍弃
						OSSUploadUtils ossUploadUtils = new OSSUploadUtils();
						// 图片上传OSS
						ossUploadUtils.uploadFile(OSSFilePath.USERHEAD + newName, MFhead);
						// 关闭OSS客户端
						ossUploadUtils.closeOssClient();
//						MFhead.transferTo(new File(dirFile.getPath() + "/" + newName));
						input.setHead_sculpture(OSSFilePath.OSSDOMAIN + "/userhead/" + newName);
					}
					if (userService.updateByUserUuid(input) > 0) {
						result.setCode(1);
						result.setMsg("操作成功!");
					} else {
						result.setCode(99);
						result.setMsg("操作失败：更新失败");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(500);
			result.setMsg(e.getMessage());
		}
		return result;
	}

	@RequestMapping("accountIsExist.do")
	@ResponseBody
	public Result accountIsExist(HttpServletRequest request, HttpServletResponse response) {
		Result result = new Result(1);
		String account = request.getParameter("account");
		try {
			int i = userService.accountCount(account);
			result.setCode(1);
			result.setMsg("获取成功");
			result.setData(i > 0 ? true : false);
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(500);
			result.setMsg("系统错误：" + e.getMessage());
		}
		return result;
	}

	/**
	 * 修改密码
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("updatepwd.do")
	@ResponseBody
	public Result updatepwd(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Result result = new Result(1);
		String password = request.getParameter("password");
		String password2 = request.getParameter("password2");
		Admin admin = super.getLogind();
		User user = new User();
		user.setUuid(admin.getUser_uuid());
		try {
			if (!password.equals(password2)) {
				result.setCode(97);
				result.setMsg("修改密码失败：两次输入的密码不一致");
			} else {
				user.setPassword(new MD5().getMD5(password2));
				int i = userService.updateByUserUuid(user);
				if (i > 0) {
					result.setCode(1);
					result.setMsg("修改密码成功");
					request.getSession().removeAttribute("user");
				} else {
					result.setCode(99);
					result.setMsg("修改密码失败");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(500);
			result.setMsg("修改密码失败：" + e.getMessage());
		}
		return result;
	}
}
